package com.gzxx.domain.bo;

import com.google.common.collect.Lists;
import com.gzxx.domain.base.RequestPage;
import com.gzxx.domain.po.SysRole;
import com.gzxx.domain.po.SysRoleMenu;
import com.gzxx.util.SysLoginUserHelper;
import lombok.Builder;
import lombok.Getter;
import lombok.ToString;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.util.Assert;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * SysRoleBO
 *
 * @author chenjing
 */
@Builder
@Getter
@ToString
public class SysRoleBO {

    private Long id;
    /**
     * 角色名称
     */
    private String roleName;
    /**
     * 角色描述
     */
    private String roleDesc;
    /**
     * 状态
     */
    private Integer status;
    /**
     * 创建人
     */
    private Long createBy;
    /**
     * 更新人
     */
    private Long updateBy;
    private Date createTime;
    private Date updateTime;
    /**
     * 关联菜单id
     */
    private List<Long> menuIds;
    /**
     * 分页
     */
    private RequestPage page;


    public Map<?, ?> queryParams() throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        return BeanMap.create(this);
    }

    /**
     * 创建角色
     */
    public SysRole create() {
        return SysRole.builder()
                .roleDesc(this.roleDesc)
                .roleName(this.roleName)
                .createBy(SysLoginUserHelper.getLoginUserId())
                .build();
    }

    /**
     * 编辑角色
     */
    public SysRole edit() {
        Assert.state(this.id > 0L, "SysRole must provide update identifier.");

        return SysRole.builder().
                id(this.id)
                .roleDesc(this.roleDesc)
                .roleName(this.roleName)
                .updateBy(SysLoginUserHelper.getLoginUserId())
                .build();
    }

    /**
     * 创建角色菜单关系
     */
    public List<SysRoleMenu> createRoleMenu(Long roleId) {
        List<SysRoleMenu> list = Lists.newArrayList();
        this.menuIds.forEach(menuId -> {
            SysRoleMenu menu = SysRoleMenu.builder()
                    .menuId(menuId)
                    .roleId(roleId)
                    .build();
            list.add(menu);
        });
        return list;
    }

    /**
     * 更改角色状态
     */
    public SysRole changeStatus() {
        Assert.state(this.id > 0L, "SysRole must provide update identifier.");
        return SysRole.builder()
                .id(this.id)
                .status(this.status)
                .updateBy(SysLoginUserHelper.getLoginUserId())
                .build();
    }
}
